package com.yaoweigroup.community.ui.bm;

import java.io.Serializable;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONObject;

import com.alipay.android.app.sdk.AliPay;
import com.hcinfos.gsoo.pay.Keys;
import com.hcinfos.gsoo.pay.Rsa;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.config.Common;
import com.yaoweigroup.community.config.Constant;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.Group;
import com.yaoweigroup.community.enity.MenuInfo;
import com.yaoweigroup.community.enity.ShopDetail;
import com.yaoweigroup.community.enity.UserInfo;
import com.yaoweigroup.community.ui.base.LoginActivity;
import com.yaoweigroup.community.ui.base.MyProfileActivity;
import com.yaoweigroup.community.ui.my.MyOrderActivity;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.LoginUtil;
import com.yaoweigroup.community.util.SharePreferenceUtil;
import com.yaoweigroup.community.util.Tools;
import com.yaoweigroup.community.util.UtilHttp;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.Profile;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class OrderSubmitActivity extends Activity implements OnClickListener {

	private RelativeLayout left_rl;
	private TextView state_tv;
	private LinearLayout shop_detail_rl;
	private TextView shopName_tv;
	private TextView phone_tv;
	private TextView time_tv;
	private TextView take_man_tv;
	private TextView take_tel_tv;
	private TextView take_address_tv;
	private TextView order_num_tv;
	private Button cancel_btn;
	private Button pay_btn;
	private Button submit_btn;
	private Dialog dialog;
	private LinearLayout address_ll;
	private SharePreferenceUtil util;
	private Button log_btn;
	private LinearLayout menu_ll;
	private TextView center_tv;
	private TextView total_tv;
	private Group group = null;

	public final int SUBMIT_SUCCESS = 0x2210;
	public final int SUBMIT_FAIL = SUBMIT_SUCCESS + 1;
	public final int NEED_LOGIN = SUBMIT_SUCCESS + 2;
	public final int RQF_PAY = SUBMIT_SUCCESS + 3;

	private ObjectMapper mapper;
	private ShopDetail detail;
	private int type;

	private TextView pay_style_tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ordersubmit);

		mapper = new ObjectMapper();
		util = new SharePreferenceUtil(this, Constant.prf);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		log_btn = (Button) findViewById(R.id.log_btn);
		log_btn.setOnClickListener(this);
		dialog = DialogUtil.createWaitDialog(this, "订单提交中..");
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);
		pay_style_tv = (TextView) findViewById(R.id.pay_style_tv);
		center_tv = (TextView) findViewById(R.id.center_tv);
		menu_ll = (LinearLayout) findViewById(R.id.menu_ll);
		address_ll = (LinearLayout) findViewById(R.id.address_ll);
		state_tv = (TextView) findViewById(R.id.state_tv);
		shop_detail_rl = (LinearLayout) findViewById(R.id.shop_detail_rl);
		shopName_tv = (TextView) findViewById(R.id.shopName_tv);
		phone_tv = (TextView) findViewById(R.id.phone_tv);
		time_tv = (TextView) findViewById(R.id.time_tv);
		take_man_tv = (TextView) findViewById(R.id.take_man_tv);
		take_tel_tv = (TextView) findViewById(R.id.take_tel_tv);
		take_address_tv = (TextView) findViewById(R.id.take_address_tv);
		order_num_tv = (TextView) findViewById(R.id.order_num_tv);
		cancel_btn = (Button) findViewById(R.id.cancel_btn);
		cancel_btn.setOnClickListener(this);
		pay_btn = (Button) findViewById(R.id.pay_btn);
		pay_btn.setOnClickListener(this);
		submit_btn = (Button) findViewById(R.id.submit_btn);
		submit_btn.setOnClickListener(this);
		total_tv = (TextView) findViewById(R.id.total_tv);
		createPayDialog();
		type = getIntent().getIntExtra("type", 1);
		if (type == 0) {
			// group
			group = (Group) getIntent().getSerializableExtra("detail");
			View view = LayoutInflater.from(this).inflate(
					R.layout.order_menu_item, null);
			TextView name_tv = (TextView) view.findViewById(R.id.name_tv);
			TextView price_tv = (TextView) view.findViewById(R.id.price_tv);
			TextView num_tv = (TextView) view.findViewById(R.id.num_tv);
			name_tv.setText(group.getPname());
			price_tv.setText("¥" + group.getNewprice());
			num_tv.setText(group.getNum() + "份   ×");
			total_tv.setText("共计:" + group.getNum() + "份，"
					+ Tools.round(group.getNum() * group.getNewprice(), 3)
					+ "元");
			total = Tools.round(group.getNum() * group.getNewprice(), 3);
			menu_ll.addView(view);
			shop_detail_rl.setVisibility(View.GONE);
			ordertype = "团购";
		} else {
			detail = (ShopDetail) getIntent().getSerializableExtra("detail");
			View view = LayoutInflater.from(this).inflate(
					R.layout.order_menu_item, null);
			TextView name_tv = (TextView) view.findViewById(R.id.name_tv);
			TextView price_tv = (TextView) view.findViewById(R.id.price_tv);
			TextView num_tv = (TextView) view.findViewById(R.id.num_tv);
			name_tv.setText(detail.getName());
			price_tv.setText("¥" + detail.getPrice());
			num_tv.setText(detail.getNum() + "份   ×");
			total = Tools.round(detail.getNum() * detail.getPrice(), 3);
			total_tv.setText("共计:" + detail.getNum() + "份，"
					+ Tools.round(detail.getNum() * detail.getPrice(), 3) + "元");
			menu_ll.addView(view);
			shop_detail_rl.setVisibility(View.GONE);
			ordertype = "商品";
		}
	}

	private UserInfo user;

	@Override
	protected void onResume() {
		super.onResume();
		user = (UserInfo) util.loadObject("user");
		if (user == null) {
			cancel_btn.setVisibility(View.GONE);
			pay_btn.setVisibility(View.GONE);
			submit_btn.setVisibility(View.GONE);
			log_btn.setVisibility(View.VISIBLE);
			address_ll.setVisibility(View.GONE);

		} else {
			log_btn.setVisibility(View.GONE);
			address_ll.setVisibility(View.VISIBLE);
			if (orderState == 0) {
				submit_btn.setVisibility(View.VISIBLE);
			} else {
				submit_btn.setVisibility(View.GONE);

			}
			address = user.getAddress();
			if (address.length() == 0) {
				address = "暂无";
			}
			take_man_tv.setText("收件人      " + user.getUsername());
			take_tel_tv.setText("联系方式      " + user.getPhone());
			take_address_tv.setText("联系地址      " + address);
		}
	}

	private String address = null;
	private String orderNum = null;
	private int orderState = 0;// 0 表示未提交 1表示 提交
	private String ordertype = "团购";

	/**
	 * 下订单
	 */
	private void submitOrder() {
		HttpUtils http = UtilHttp.getHttpUtils(this);

		RequestParams params = new RequestParams();
		user = (UserInfo) util.loadObject("user");
		if (user == null) {
			Toast.makeText(OrderSubmitActivity.this, "亲 请先登录，再操作!", 500).show();
			return;
		}
		if (user.getAddress().length() == 0) {
			Intent intent = new Intent(this, MyProfileActivity.class);
			startActivity(intent);
			Toast.makeText(OrderSubmitActivity.this, "亲 请去完善你的地址!", 500).show();
			return;
		}
		dialog.show();
		JsonUtil jsonUtil = new JsonUtil();
		LogUtil.d("wxf", jsonUtil.toString());
		jsonUtil.add("Uid", user.getUid());
		jsonUtil.add("consignee", user.getUsername());
		jsonUtil.add("phoneNum", user.getPhone());
		jsonUtil.add("adress", user.getAddress());
		jsonUtil.add("remark", "");
		jsonUtil.add("ordertype", ordertype);
		String payStr = "在线付款";
		if (payType == 0) {
			payStr = "在线付款";
		} else {
			payStr = "货到付款";
		}
		jsonUtil.add("receovingWay", payStr);
		jsonUtil.add("ordersource", "手机APP");
		StringEntity enity = null;
		try {
			if (type == 0) {
				for (JsonUtil util : getGroupStr()) {
					jsonUtil.add("orderdetailargs", util);
				}
			} else {
				for (JsonUtil util : getShopStr()) {
					jsonUtil.add("orderdetailargs", util);
				}
			}

			LogUtil.d("wxf", "param=" + jsonUtil.toString());
			enity = new StringEntity(jsonUtil.toString(), "UTF-8");
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.submitOrder, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String message = obj.getString("message");
							if (state == 200) {
								orderNum = obj.getString("orderNum");
								handler.sendEmptyMessage(SUBMIT_SUCCESS);
							} else if (state == 10000) {
								handler.sendEmptyMessage(NEED_LOGIN);

							} else {
								handler.sendEmptyMessage(SUBMIT_FAIL);

							}
						} catch (Exception e) {
							handler.sendEmptyMessage(SUBMIT_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(SUBMIT_FAIL);

					}

				});
	}

	private List<JsonUtil> getGroupStr() {

		List<JsonUtil> jsons = new ArrayList<JsonUtil>();
		JsonUtil utils = new JsonUtil();
		utils.add("productName", group.getPname());
		utils.add("groupid", group.getId() + "");
		utils.add("productCount", group.getNum());
		utils.add("pid", group.getPid());
		// utils.add("purchaseprice", group.get)
		jsons.add(utils);
		return jsons;
	}

	private List<JsonUtil> getShopStr() {
		List<JsonUtil> jsons = new ArrayList<JsonUtil>();
		JsonUtil utils = new JsonUtil();
		utils.add("productName", detail.getName());
		utils.add("purchaseprice", detail.getPrice() + "");
		utils.add("productCount", detail.getNum());
		utils.add("pid", detail.getPid());
		utils.add("purchaseprice", detail.getPurchaseprice());
		jsons.add(utils);
		return jsons;
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		case R.id.cancel_btn:
			Intent intent = new Intent(this, MyOrderActivity.class);
			startActivity(intent);
			finish();
			break;
		case R.id.pay_btn:
			pay();
			break;
		case R.id.submit_btn:
			if (type == 0) {
				submitOrder();
			} else {
				payDialog.show();
			}

			break;
		case R.id.log_btn:
			intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			break;
		}
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {

			case RQF_PAY:
				Intent my = new Intent(OrderSubmitActivity.this,
						MyOrderActivity.class);
				startActivity(my);
				finish();
				break;
			case SUBMIT_SUCCESS:
				orderState = 1;
				dialog.dismiss();
				if (payType == 0) {

					order_num_tv.setText("订单号      " + orderNum);
					order_num_tv.setVisibility(View.VISIBLE);
					pay_btn.setVisibility(View.VISIBLE);
					cancel_btn.setVisibility(View.VISIBLE);
					submit_btn.setVisibility(View.GONE);

				} else {

					Intent intent = new Intent(OrderSubmitActivity.this,
							MyOrderActivity.class);
					startActivity(intent);
					finish();
				}
				break;
			case SUBMIT_FAIL:
				dialog.dismiss();
				break;
			case NEED_LOGIN:
				LoginUtil.isLoginSuccess(OrderSubmitActivity.this, handler,
						mapper);

				break;
			case LoginUtil.LOGIN_FAIL:
				dialog.dismiss();
				break;
			case LoginUtil.LOGIN_SUCCESS:
				submitOrder();
				break;
			}
		};
	};

	/**
	 * 支付宝支付模块
	 * 
	 */
	private void pay() {
		String info = getOrderInfo();
		String sign = Rsa.sign(info, Keys.PRIVATE);
		sign = URLEncoder.encode(sign);
		info += "&sign=\"" + sign + "\"&" + getSignType();
		final String orderInfo = info;
		new Thread() {
			public void run() {
				AliPay alipay = new AliPay(OrderSubmitActivity.this, handler);

				// 设置为沙箱模式，不设置默认为线上环境
				// alipay.setSandBox(true);
				String result = alipay.pay(orderInfo);
				Message msg = handler.obtainMessage();
				msg.what = RQF_PAY;
				msg.obj = result;
				handler.sendMessage(msg);
				LogUtil.d("wxf", "result = " + result);
			}
		}.start();
	}

	private double total = 0;

	private String getOrderInfo() {

		String detailStr = "";
		if (type == 0) {
			detailStr = group.getPname() + "," + group.getNum();
		} else {
			detailStr = detail.getName() + "," + detail.getNum();
		}

		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&out_trade_no=\"");
		sb.append(orderNum);
		sb.append("\"&subject=\"");
		sb.append("订单");
		sb.append("\"&body=\"");
		sb.append(detailStr);
		sb.append("\"&total_fee=\"");
		sb.append(total + "");
		sb.append("\"&notify_url=\"");

		// 网址需要做URL编码
		sb.append(URLEncoder
				.encode("http://www.smartcity.sh/Shared/notify_url"));
		// sb.append("http://www.smartcity.sh/Shared/notify_url");
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	private Dialog payDialog;
	private int payType = 0;// 0 在线支付 1货到付款

	private void createPayDialog() {
		LayoutInflater inflater = LayoutInflater.from(this);
		LinearLayout dialog_rl = (LinearLayout) inflater.inflate(
				R.layout.pay_dialog_view, null);
		TextView online_tv = (TextView) dialog_rl.findViewById(R.id.online_tv);

		TextView crash_tv = (TextView) dialog_rl.findViewById(R.id.crash_tv);
		payDialog = new Dialog(this, R.style.QuitDialog);
		payDialog.setContentView(dialog_rl);

		online_tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				payDialog.dismiss();
				payType = 0;
				pay_style_tv.setText("付款方式      在线支付");

				submitOrder();

			}
		});
		crash_tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				payDialog.dismiss();
				payType = 1;
				pay_style_tv.setText("付款方式      货到付款");
				submitOrder();
			}
		});

		Window dialogWindow = payDialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = (int) (200 * Common.PROPORTION); // 宽度
		lp.height = (int) (100 * Common.PROPORTION); // 高度
		dialogWindow.setAttributes(lp);
	}
}
